<?php

//PLUGIN type=action
//PLUGIN name=user.save
//PLUGIN desc=Enables you to save user information
//PLUGIN group=native

$userlist = unserialize(file_get_contents(_SETTINGSPATH_ . "/userdata.ser"));

if (!empty($_POST['username']))
    $_POST['username'] = strtolower($_POST['username']);
if (!empty($options['user']))
    $options['user'] = strtolower($options['user']);

if (isset($_SESSION['user']))
{
    if (empty($options['user']) && $_SESSION['user']['permissions']['create']['user']) // if trying to save a new username, and user has permission
    { // new user
        $_POST['user']['deleteable'] = (empty($_POST['user']['deleteable']) || strtolower($_POST['user']['deleteable']) != "false");

        // defaults
        if (empty($_POST['user']['password']))
            $_POST['user']['password'] = "password";
        if (empty($_POST['user']['name']))
            $_POST['user']['name'] = "Unavngivet bruger";
        if (empty($_POST['user']['permissions']['id']))
            $_POST['user']['permissions']['id'] = "guest";


        // hash password
        $_POST['user']['password'] = sha1($_POST['user']['password']);

        $userlist[$_POST['username']] = $_POST['user'];

        //sort the list (looks nicer)
        ksort($userlist);


        //save list back to file
        file_put_contents(_SETTINGSPATH_ . "/userdata.ser", serialize($userlist));
    }
    elseif ($_SESSION['user']['permissions']['modify']['user'] == "all" ||
            $_SESSION['user']['permissions']['modify']['user'] == "own" && $options['user'] == $_SESSION['username'])
    { // Save old user
        //
        //RENAME
        if ($_POST['username'] != $options['user'] && isset($userlist[$options['user']]))
        {
            $userlist[$_POST['username']] = $userlist[$options['user']];
            unset($userlist[$options['user']]);
            $options['user'] = $_POST['username'];
        }

        //Changes to permissions allowed? (only admin)
        if ($_SESSION['user']['permissions']['id'] != "administrator")
            $_POST['user']['permissions']['id'] = 'guest';

        //Unset password if field = empty
        if (empty($_POST['user']['password']))
            unset($_POST['user']['password']);
        else
            $_POST['user']['password'] = sha1($_POST['user']['password']);

        //Save data part to list
        $userlist[$options['user']] = array_merge($userlist[$options['user']], $_POST['user']);

        //sort the list (looks nicer)
        ksort($userlist);
        //save list back to file
        file_put_contents(_SETTINGSPATH_ . "/userdata.ser", serialize($userlist));
    }
}
header("Location:?q=command:cms;view:cms.users;");
?>